import os 
import torch
from torch import nn
from torch.utils.data import Dataset, DataLoader
from torchvision import datasets,transforms


#检测设备可用性
device = (
    "cuda"
    if torch.cuda.is_available()
    else "mps"
    if torch.backends.mps.is_available()
    else "cpu"
)
print(f"Using {device} devices")

class NeuralNetwork(nn.Module):
    def __init__(self):
        super().__init__()
        self.flatten = nn.Flatten()
        self.linear_relu_stack = nn.Sequential(
            nn.Linear(28 * 28, 512),
            nn.ReLU(),
            nn.Linear(512, 512),
            nn.ReLU(),
            nn.Linear(512, 10),
        )

    def forward(self, x):
        x = self.flatten(x)
        logits = self.linear_relu_stack(x)
        return logits


#显示模型结构
model = NeuralNetwork().to(device)
print(model)

X = torch.rand(1, 28, 28, device=device)
logits = model(X)
pred_probab = nn.Softmax(dim=1)(logits)
y_pred = pred_probab.argmax(1)
print(f"Predicted class: {y_pred}")

#模型层
#创建一个简单的28，28RGB 图像
input_image = torch.rand(3,28,28)
print(input_image.size())

#28*28*3 = 748*3
#Flatten层 将输入展平为一维向量
flatten = nn.Flatten()
flat_image = flatten(input_image)
print(flat_image.size())

#线性层 它使用起储存的权重和偏差对输入进行线性变换
layer1 = nn.Linear(in_features=28*28, out_features=20)
hidden1 = layer1(flat_image)
print(hidden1.size())

#ReLU 激活函数
print(f"Before ReLU: {hidden1}\n\n")
hidden1 = nn.ReLU()(hidden1)
print(f"After ReLU: {hidden1}")

#nn.sorftmax
#神经网络的最后一个线性层返回_logits_，即每个类别的未归一化分数。为了将这些分数转换为概率分布，我们使用`nn.Softmax`层。这将使logits被缩放到[0,1]之间，表示模型对每个类的预测概率。dim参数指定了沿哪个轴进行归一化。
#简而言之sorftmax函数通常被用于将输出转换为概率分布

softmax = nn.Softmax(dim=1)
pred_probability = softmax(logits)

#迭代显示模型参数

print(f"模型结构如下:{model}\n\n")

for name,param in model.named_parameters():
    #打印每个参数的名称、大小和前两个值
    print(f"Layer:{name} | Size:{param.size} | Values : {param[:2]} \n ")

